package com.sf.guava.basic;

import com.google.common.base.Throwables;
import java.io.IOException;

/**
 * @Classname ThrowablesTest
 * @Description 异常
 * @Date 2019/12/11 0011 17:07
 * @Created by 埔枘
 */
public class ThrowablesTest {

    public static void main(String[] args) {
        ThrowablesTest throwablesTest = new ThrowablesTest();
        try {
            throwablesTest.showcaseThrowables();
        } catch (InvalidInputException e) {
            //get the root cause
            System.out.println(Throwables.getRootCause(e));
        }catch (Exception e) {
            //get the stack trace in string format
            System.out.println(Throwables.getStackTraceAsString(e));
        }


    }
    public void showcaseThrowables() throws InvalidInputException{
        try {
            sqrt(-3.0);
        } catch (Throwable e) {
            //此方法 已不推荐 使用
//            Throwables.propagateIfInstanceOf(e, InvalidInputException.class);
            // 如果是 InvalidInputException 才抛出
            Throwables.throwIfInstanceOf(e, InvalidInputException.class);
            // 抛出不检查的异常
            Throwables.throwIfUnchecked(e);

        }
    }

    public void showcaseThrowables1(){
        try {
            int[] data = {1,2,3};
            getValue(data, 4);
        } catch (Throwable e) {
            Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class);
            Throwables.propagate(e);
        }
    }

    public double sqrt(double input) throws InvalidInputException{
        if(input < 0) throw new InvalidInputException();
        return Math.sqrt(input);
    }

    public double getValue(int[] list, int index) throws IndexOutOfBoundsException {
        return list[index];
    }

    public void dummyIO() throws IOException {
        throw new IOException();
    }
}

class InvalidInputException extends Exception {
}

